package com.stylefeng.guns.rest.modular.user;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.api.user.UserAPI;
import com.stylefeng.guns.api.user.vo.*;
import com.stylefeng.guns.core.util.HttpUtils;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.api.user.vo.UserDetailInfo;
import com.stylefeng.guns.rest.common.util.UserVailConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Component
@Service(interfaceClass = UserAPI.class)
public class UserServiceImpl implements UserAPI {

    @Autowired
    private SnailUserMapper snailUserMapper;

    @Autowired
    private SnailUserExpMapper snailUserExpMapper;
    @Autowired
    private SnailHistoryMapper snailHistoryMapper;
    @Autowired
    private SnailClassMapper snailClassMapper;
    @Autowired
    private SnailFocusMapper snailFocusMapper;
    @Autowired
    private SnailJobMapper snailJobMapper;
    @Autowired
    private SnailJobDetailMapper snailJobDetailMapper;

    @Autowired
    private UserVailConfig userVailConfig;

    @Override
    public boolean register(UserModel userModel) {
        // 将注册信息实体转换为数据实体[snail_user]
        SnailUser snailUser = new SnailUser();
        snailUser.setUsername(userModel.getUsername());
        snailUser.setNickname(userModel.getNickname());
        // 创建时间和修改时间 -> current_timestamp

        // 数据加密 【MD5混淆加密 + 盐值 -> Shiro加密】
        String md5Password = MD5Util.encrypt(userModel.getPassword());
        snailUser.setPassword(md5Password); // 注意

        // 将数据实体存入数据库
        Integer insert = snailUserMapper.insert(snailUser);
        if(insert>0){
            return true;
        }else{
            return false;
        }
    }


    @Override
    public int login(String username, String password) {
        // 根据登陆账号获取数据库信息
        SnailUser moocUserT = new SnailUser();
        moocUserT.setUsername(username);

        SnailUser result = snailUserMapper.selectOne(moocUserT);

        // 获取到的结果，然后与加密以后的密码做匹配
        if(result!=null && result.getUuid()>0){
            String md5Password = MD5Util.encrypt(password);
            if(result.getPassword().equals(md5Password)){
                return result.getUuid();
            }
        }
        return 0;
    }

    @Override
    public boolean checkUsername(String username) {
        EntityWrapper<SnailUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("username",username);
        Integer result = snailUserMapper.selectCount(entityWrapper);
        if(result!=null && result>0){
            return false;
        }else{
            return true;
        }
    }

    @Override
    public boolean checkNickname(String nickname) {
        EntityWrapper<SnailUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("nickname",nickname);
        Integer result = snailUserMapper.selectCount(entityWrapper);
        if(result!=null && result>0){
            return false;
        }else{
            return true;
        }
    }

    private UserInfoModel do2UserInfo(SnailUser snailUser){
        UserInfoModel userInfoModel = new UserInfoModel();

        userInfoModel.setUuid(snailUser.getUuid());
        userInfoModel.setUpdateTime(snailUser.getUpdateTime().getTime());
        userInfoModel.setUsername(snailUser.getUsername());
        userInfoModel.setNickname(snailUser.getNickname());
        userInfoModel.setBeginTime(snailUser.getBeginTime().getTime());
        userInfoModel.setAnchor(snailUser.getAnchor());
        userInfoModel.setCertStatus(snailUser.getCertStatus());
        userInfoModel.setHeadAddr(snailUser.getHeadAddr());
        userInfoModel.setIntegrals(snailUser.getIntegrals());
        userInfoModel.setIntegralsZhu(snailUser.getIntegralsZhu());

        return userInfoModel;
    }

    @Override
    @Cacheable(value = "redisCache",key = "'redis_user_'+#uuid")
    public UserInfoModel getUserInfo(int uuid) {
        // 根据主键查询用户信息 [MoocUserT]
        SnailUser moocUserT = snailUserMapper.selectById(uuid);
        // 将MoocUserT转换UserInfoModel
        UserInfoModel userInfoModel = do2UserInfo(moocUserT);
        // 返回UserInfoModel
        return userInfoModel;
    }

//    更新数据后，更新缓存
    @Override
    @CachePut(value = "redisCache",condition = "#result != 'null'",key = "'redis_user_'+#result.uuid")
    public UserInfoModel updateUserInfo(UserInfoModel userInfoModel) {
        // 将传入的参数转换为DO 【MoocUserT】
        SnailUser snailUser = new SnailUser();
        snailUser.setUuid(userInfoModel.getUuid());
//        snailUser.setUsername(userInfoModel.getUsername());
        snailUser.setHeadAddr(userInfoModel.getHeadAddr());
        snailUser.setNickname(userInfoModel.getNickname());
//        snailUser.setLifeState(Integer.parseInt(userInfoModel.getLifeState()));
//        snailUser.setBirthday(userInfoModel.getBirthday());
//        snailUser.setBiography(userInfoModel.getBiography());
//        snailUser.setBeginTime(null);
//        snailUser.setHeadUrl(userInfoModel.getHeadAddress());
//        snailUser.setEmail(userInfoModel.getEmail());
//        snailUser.setAddress(userInfoModel.getAddress());
//        snailUser.setUserPhone(userInfoModel.getPhone());
//        snailUser.setUserSex(userInfoModel.getSex());
        snailUser.setUpdateTime(null);

        // DO存入数据库
        Integer integer = snailUserMapper.updateById(snailUser);
        if(integer>0){
            // 将数据从数据库中读取出来
            UserInfoModel userInfo = getUserInfo(snailUser.getUuid());
            System.out.println(userInfo.getHeadAddr());
            // 将结果返回给前端
            return userInfo;
        }else{
            return null;
        }
    }

    private JSONObject getCretInfo(UserValidRequestVO userValidRequestVO){
        String host1 = userVailConfig.getHost();
        String path1 = userVailConfig.getPath();
        String method1 = userVailConfig.getMethod();
        String appcode1 = userVailConfig.getAppcode();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode1);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("idCard", userValidRequestVO.getIdcard());
        querys.put("name", userValidRequestVO.getRealname());
        HttpResponse response = null;
        try {
            response = HttpUtils.doGet(host1, path1, method1, headers, querys);
            //System.out.println(response.toString());如不输出json, 请打开这行代码，打印调试头部状态码。
            //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
            //获取response的body
            String result = EntityUtils.toString(response.getEntity());
            JSONObject responseBody = new JSONObject(result);
            return responseBody;
        } catch (Exception e) {
            log.error("实名认证失败"+e);
            return null;
        }
    }

    @Override
    @CachePut(value = "redisCache",condition = "#result != 0",key = "'redis_user_'+#uuid")
    public int authentication(Integer uuid,UserValidRequestVO userValidRequestVO) {
        JSONObject responseBody = this.getCretInfo(userValidRequestVO);
        try {
            if(responseBody.get("status").toString().equals("01")){
                //实名认证通过
                //转换为实体对象
                SnailUserExp snailUserExp = new SnailUserExp();
                snailUserExp.setUid(uuid);
                snailUserExp.setRealname(responseBody.get("name").toString());
                snailUserExp.setSex(responseBody.get("sex").toString());
                snailUserExp.setIdcard(responseBody.get("idCard").toString());
                snailUserExp.setArea(responseBody.get("area").toString());
                snailUserExp.setProvince(responseBody.get("province").toString());
                snailUserExp.setCity(responseBody.get("city").toString());
                snailUserExp.setPrefecture(responseBody.get("prefecture").toString());
                snailUserExp.setBirthday(responseBody.get("birthday").toString());
                snailUserExp.setAddrCode(responseBody.get("addrCode").toString());
                snailUserExp.setLastCode(responseBody.get("lastCode").toString());
                //保存用户信息
                int res = snailUserExpMapper.insertUserExp(snailUserExp);
                if(res > 0){
                    //更改用户实名状态为：1  已认证
                    int i = snailUserMapper.updateCertStatus(uuid);
                    if(i > 0){
                        return i;
                    }else{
                        log.error("更改用户实名状态失败");
                        return 0;
                    }
                }else {
                    log.error("实名保存用户信息失败");
                    return 0;
                }
            }else {
                return 0;
            }
        } catch (Exception e) {
            log.error("实名认证失败"+e);
            return 0;
        }
    }

    @Override
    public boolean isNotValid(int uid) {
        SnailUserExp userValidResponseVO = new SnailUserExp();
        userValidResponseVO.setUid(uid);
        SnailUserExp snailUserExp = snailUserExpMapper.selectOne(userValidResponseVO);
        if(snailUserExp != null && snailUserExp.getUid() != 0){
            //已经验证过，不用再验证
            return false;
        }else {
            return true;
        }
    }

    //验证身份证是否已被使用
    @Override
    public boolean validIdCard(String idCard) {
        SnailUserExp userValidResponseVO = new SnailUserExp();
        userValidResponseVO.setIdcard(idCard);
        SnailUserExp snailUserExp = snailUserExpMapper.selectOne(userValidResponseVO);
        if(snailUserExp != null && snailUserExp.getIdcard() != ""){
            //身份证已经被验证过，不能再验证
            return false;
        }else {
            return true;
        }
    }

    @Override
    public Map getHistorys(int userId) {
        EntityWrapper ew = new EntityWrapper();
        ew.eq("user_id",userId);
        ew.orderBy("time",false);
        List<SnailHistory> list = snailHistoryMapper.selectList(ew);
        HistoryInfoVO historyInfoVO = new HistoryInfoVO();
        Map historyMap = new HashMap();
        List timeList = new ArrayList();
        //获取时间列表
        for (SnailHistory history:list){
            String timeFormat = getDate(history.getTime());
            if(timeList.contains(timeFormat)){
                continue;
            }else {
                timeList.add(timeFormat);
            }
        }
        for(Object time:timeList){
            List list2 = new ArrayList();
            for(SnailHistory history:list){
                if(time.equals(getDate(history.getTime()))){
                    list2.add(history);
                }
            }
            historyMap.put(time,list2);
        }
        return historyMap;
    }

    //添加浏览记录
    public int addHistory(String content,String picPath,String uid,String livePath,Integer cid,String guid){
        SnailHistory history = new SnailHistory();
        history.setTitle(content);
        history.setHeadAddr(picPath);
        history.setUserId(uid);
        history.setLiveAddr(livePath);
        //获取主播名
        String nickname = snailUserMapper.selectUserByGuid(guid);
        history.setName(nickname);
        System.out.println(nickname);
        //获取所有栏目分类
        List<SnailClass> snailClasses = snailClassMapper.selectList(null);
        for (SnailClass snailClass:snailClasses){
            if(cid.equals(snailClass.getId())){
                history.setCategoryName(snailClass.getType());
            }
        }

        return snailHistoryMapper.insert(history);
    }

    @Override
    public int toFocus(int fromUserId, int toUserId) {
        SnailFocus snailFocus = new SnailFocus();
        snailFocus.setFromUserId(fromUserId);
        snailFocus.setToUserId(toUserId);

        return snailFocusMapper.insert(snailFocus);
    }

    @Override
    public int delFoucs(int fromUserId, int toUserId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("from_user_id",fromUserId);
        entityWrapper.eq("to_user_id",toUserId);
        return snailFocusMapper.delete(entityWrapper);
    }

    @Override
    public UserDetailInfo getUserDetail(int uid) throws ParseException {
        UserDetailInfo userDetail = snailUserMapper.getUserDetail(uid);
        if(userDetail == null){
            SnailUser snailUser = snailUserMapper.selectById(uid);
            UserDetailInfo userDetailInfo = new UserDetailInfo();
            userDetailInfo.setNickname(snailUser.getNickname());
            userDetailInfo.setUsername(snailUser.getUsername());
            userDetailInfo.setHead_path(snailUser.getHeadAddr());
            //获取订阅数
            Integer focusNum = snailUserMapper.getFocusNum(uid);
            //获取粉丝数
            Integer fansNum = snailUserMapper.getFansNum(uid);
            if(focusNum == null){
                focusNum =0;
            }
            if(fansNum == null){
                fansNum =0;
            }
            userDetailInfo.setFansNum(fansNum);
            userDetailInfo.setFocusNum(focusNum);
            return userDetailInfo;
        }
        //获取订阅数
        Integer focusNum = snailUserMapper.getFocusNum(uid);
        //获取粉丝数
        Integer fansNum = snailUserMapper.getFansNum(uid);
        if(focusNum == null){
            focusNum =0;
        }
        if(fansNum == null){
            fansNum =0;
        }
        userDetail.setFansNum(fansNum);
        userDetail.setFocusNum(focusNum);
        userDetail.setAge(getAge(userDetail.getBirthday()));
        return userDetail;
    }

    @Override
    public JobVO getJobs(int uid) {
        List userJobList = new ArrayList();
        List actJobList = new ArrayList();
        List zhuJobList = new ArrayList();
        userJobList = snailJobMapper.getUserJobs(uid);
        zhuJobList = snailJobMapper.getAouJobs(uid);
        actJobList = snailJobMapper.getActJobs(uid);
        System.out.println("zhuJobList = " + zhuJobList);
        if(userJobList==null || userJobList.size() <=0){
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("type",1);
            userJobList = snailJobMapper.selectList(entityWrapper);
        }
        if(zhuJobList==null || zhuJobList.size() <=0){
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("type",2);
            zhuJobList = snailJobMapper.selectList(entityWrapper);
        }
        if(actJobList==null || actJobList.size() <=0){
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("type",3);
            actJobList = snailJobMapper.selectList(entityWrapper);
        }
        JobVO jobVO = new JobVO();
        jobVO.setActJobList(actJobList);
        jobVO.setUserJobList(userJobList);
        jobVO.setZhuJobList(zhuJobList);
        return jobVO;
    }

    @Override
    public int toJoin(int uid, int jobId) {
        SnailJobDetail snailJobDetail = new SnailJobDetail();
        snailJobDetail.setJobId(jobId);
        snailJobDetail.setUserId(uid);
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("job_id",jobId);
        entityWrapper.eq("user_id",uid);
        SnailJobDetail i = snailJobDetail.selectOne(entityWrapper);
        System.out.println("********************"+i);
        if(i!=null){
            return 0;
        }
        return snailJobDetailMapper.insert(snailJobDetail);
    }

    @Override
    public List<Integer> getJobIds() {
        return snailJobMapper.getJobIds();
    }

    @Override
    public Integer countJobs() {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.ne("type",3);
        return snailJobMapper.selectCount(entityWrapper);
    }

    @Override
    public Integer countJobDetail(int uid) {
        SnailJobDetail snailJobDetail = new SnailJobDetail();
        snailJobDetail.setUserId(uid);
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.setEntity(snailJobDetail);
        return snailJobDetailMapper.selectCount(entityWrapper);
    }

    //将timestamp转为date  (年月日)
    private String getDate(Date timestamp){
        Date time = timestamp;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String timeFormat = sdf.format(time);
        return timeFormat;
    }

    //计算年龄
    private Integer getAge(String birthday) throws ParseException {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date=new Date();
        java.util.Date mydate= myFormatter.parse(birthday);
        long day=(date.getTime()-mydate.getTime())/(24*60*60*1000) + 1;
        Integer age = (int)(day/365);
        return age;
    }
}
